package com.lt.integration.jpa.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;

import java.security.SecureRandom;

/**
 * 密码工具类
 * @author xiaobin
 *
 */
public class PasswordUtils {

	private static final int SALT_SIZE = 8;

	private static SecureRandom random = new SecureRandom();

	/**
	 * 密码加密
	 * @param password
	 * @return
	 */
	public static String encrypt(String password){
		byte[] saltByte = new byte[SALT_SIZE];
		random.nextBytes(saltByte);
		String salt = HexUtil.encodeHexStr(saltByte);
		String entryPassword = SecureUtil.hmacSha1(saltByte).digestHex(password);
		return salt + entryPassword;
	}

	/**
	 * 验证码密码是否相等
	 * @param cleartextPassword 明文密码
	 * @param encryptPassword 加密密码
	 * @return
	 */
	public static Boolean validate(String cleartextPassword, String encryptPassword) {
		String salt = encryptPassword.substring(0, SALT_SIZE * 2);
		byte[] saltByte = HexUtil.decodeHex(salt);
		String pwd = salt + SecureUtil.hmacSha1(saltByte).digestHex(cleartextPassword);
		return pwd.equals(encryptPassword);
	}
}
